package com.hxh.wechat.api

import com.google.gson.JsonObject
import com.hxh.wechat.api.ThirdPartyApi.Companion.queryWeatherList
import com.hxh.wechat.util.DBUtil
import com.hxh.wechat.util.HttpUtil
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import java.io.IOException

class ThirdPartyApi {
    data class Weather(
        val date: String,
        val weather: String,
        val icon1: Any?,
        val icon2: Any?,
        val temp: String,
        val w: String,
        val wind: String,
        val icond: String,
        val iconn: String
    )

    //调用天气api
    companion object {
        fun queryWeatherList(cityName: String, onResult: (List<Weather>?) -> Unit) {
            val path = "https://query.asilu.com/weather/baidu/?city=${cityName}";
            HttpUtil.getFullPath(path)?.enqueue(
                object : Callback {
                    override fun onFailure(call: Call, e: IOException) {
                        println("Failed.")
                        println(e.stackTrace.toString())
                        onResult(null)
                    }

                    @Throws(IOException::class)
                    override fun onResponse(call: Call, response: Response) {
                        val weatherList = DBUtil.getGson().fromJson(
                            DBUtil.getGson()
                                .fromJson(response.body?.string(), JsonObject::class.java)
                                .get("weather").toString(), Array<Weather>::class.java
                        ).toList();
                        onResult(weatherList)
                    }
                })
        }
    }
}

fun main() {
    queryWeatherList("北京") {
        println(it)
    }
}